package com.vincent.jvmtest.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author vincent
 * @date 2019/3/3
 * @description
 */
public class ExpiredCache {
    private static Logger logger = LoggerFactory.getLogger(DelayedQueueDemo.class);
    private DelayQueue<DelayedVo<String>> queue = new DelayQueue<>();
    private Map<String, String> map = new ConcurrentHashMap<>(128);
    private static ExpiredCache instance;

    private ExpiredCache() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1));
        threadPoolExecutor.execute(() -> {
            while (true) {
                try {
                    DelayedVo<String> take = queue.take();
                    String key = take.getValue();
                    logger.info("remove by key = {}", key);
                    map.remove(key);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static ExpiredCache getInstance() {
        if (instance == null) {
            synchronized (ExpiredCache.class) {
                if (instance == null) {
                    instance = new ExpiredCache();
                }
            }
        }
        return instance;
    }

    public void add(String key, String value, long timeout) {
        logger.info("add cache key={}, value={}", key, value);
        this.map.put(key, value);
        this.queue.put(new DelayedVo<>(timeout, key));
    }

    public String get(String key) {
        return map.get(key);
    }
}
